package com.nwpu.am.controller.admin;

import com.nwpu.am.constant.ErrorConstant;
import com.nwpu.am.pojo.dto.RuleDTO;
import com.nwpu.am.pojo.entity.Rule;
import com.nwpu.am.pojo.entity.Knowledge;
import com.nwpu.am.result.Result;
import com.nwpu.am.service.KnowledgeService;
import com.nwpu.am.service.RuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * RuleController
 *
 * @author Fbf
 * @version 1.0
 * {@code @date} 2024/6/6
 */

@RestController
@RequestMapping("/rule")
@Slf4j
@Api(tags = "推理规则接口")
public class RuleController {

    @Resource
    private RuleService ruleService;
    @Resource
    private KnowledgeService knowledgeService;

    @GetMapping("/selectAll")
    @ApiOperation("展示推理规则")
    @RequiresPermissions("admin:rule:select")
    public List<Rule> display() {
        return ruleService.getAllRule();
    }

    @PostMapping("/add")
    @ApiOperation("添加推理规则")
    @RequiresPermissions("admin:rule:add")
    public Result<String> add(@RequestBody @Validated RuleDTO ruleDTO) {
        long premise = ruleDTO.getPremiseKnowledgeId();
        long conclusion = ruleDTO.getConclusionKnowledgeId();
        Knowledge premiseK = knowledgeService.selectById(premise);
        Knowledge conclusionK = knowledgeService.selectById(conclusion);
        // 如果前提和推论都存在
        if (premiseK != null && conclusionK != null) {
            return ruleService.addRule(ruleDTO) == 1 ?
                    Result.success() :
                    Result.error(ErrorConstant.ADD_WRONG);
        } else {
            return Result.error(ErrorConstant.UNEXPECTED_RULE);
        }
    }

    @DeleteMapping("/delete/{ruleId}")
    @ApiOperation("删除规则")
    @RequiresPermissions("admin:rule:delete")
    public Result<String> deleteById(@PathVariable("ruleId") long ruleId) {
        return ruleService.deleteRule(ruleId) == 1 ?
                Result.success() :
                Result.error(ErrorConstant.DELETE_WRONG);
    }

    @GetMapping("/select/{ruleId}")
    @ApiOperation("查找规则")
    @RequiresPermissions("admin:rule:select")
    public Rule selectById(@PathVariable("ruleId") long ruleId) {
        return ruleService.selectById(ruleId);
    }
}
